﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Midi;

namespace MIDIRemapper.DeviceInterfaces
{
    partial class DeviceInterface
    {
        void ProcessMessage(MidiType type, Channel channel, int program, int value)
        {
            List<Transformable> lt = routes.FindAll((t => t.IsMatch(type, (int)channel, program, value)));
            if (lt.Count == 0)
            {
                SendMessageByType(type, program, channel, value);
            }
            else
            {
                MidiType typeTemp;
                Channel channelTemp;
                int programTemp;
                int valueTemp;
                foreach (Transformable t in lt)
                {
                    t.GetTransformed(channel, program, value, out typeTemp, out channelTemp, out programTemp, out valueTemp);
                    SendMessageByType(typeTemp, programTemp, channelTemp, valueTemp);
                }
            }
        }

        #region Event handlers
        void inputDevice_PitchBend(PitchBendMessage msg)
        {
            //Pitch wheel value holds twice the data of standard values, so split it up.
            ProcessMessage(MidiType.Pitch_Wheel, msg.Channel, msg.Value & 127, (msg.Value >> 7) & 127);
        }

        void inputDevice_ControlChange(ControlChangeMessage msg)
        {
            ProcessMessage(MidiType.Control, msg.Channel, (int)msg.Control, msg.Value);
        }

        void inputDevice_ProgramChange(ProgramChangeMessage msg)
        {
            ProcessMessage(MidiType.Instrument, msg.Channel, (int)msg.Instrument, RANDOM_VALUE);
        }

        void inputDevice_NoteOff(NoteOffMessage msg)
        {
            ProcessMessage(MidiType.Note_Off, msg.Channel, (int)msg.Pitch, (int)msg.Velocity);
        }

        void inputDevice_NoteOn(NoteOnMessage msg)
        {
            ProcessMessage(MidiType.Note_On, msg.Channel, (int)msg.Pitch, (int)msg.Velocity);
        }
        #endregion

    }
}
